package com.quectel.grid.controller.grid;


import cn.hutool.core.date.*;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.grid.GridBusiness;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridMemberDto;
import com.quectel.core.module.grid.dto.GridMemberWorkLogDto;
import com.quectel.core.module.grid.service.GridMemberWorkLogService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.grid.controller.BaseController;
import com.quectel.grid.util.SessionHolder;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/02/03 16:42
 */
@RestController
@RequestMapping("gridMemberWorkLog")
@Tag(name = "GridMemberWorkLogController", description = "网格员工作日志相关api")
public class GridMemberWorkLogController extends BaseController {

    @DubboReference
    private GridMemberWorkLogService gridMemberWorkLogService;
    @DubboReference
    private GridService gridService;

    @Autowired
    private GridBusiness gridBusiness;

    public static final Pair<String, String> LOG_DATE_SLOT_KEY_PAIR = ImmutablePair.of("logDateBegin", "logDateEnd");


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {


        Map<String, Object> params = new HashMap<>();

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            GridMemberDto gridMember = SessionHolder.getGridMember();

            params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
            params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());

            if (gridMemberWorkLogService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridMemberWorkLogService.deleteBatch(ids);

        return Response.ok();
    }


    /**
     * 分页查询
     *
     * @param dateParam
     * @return
     */
    @GetMapping("logDates")
    @Operation(summary = "日志日期列表")
    public Response<List<String>> logDates(
            @Parameter(description = "查询日期,格式yyyy-MM") @RequestParam String dateParam,
            @Parameter(description = "网格ID") @RequestParam(required = false) Long gridId
    ) {
        GridMemberDto gridMember = SessionHolder.getGridMember();
        GridDto gridDto = null;
        if (gridId != null) {
            gridDto = gridBusiness.checkGridMemberPermission(gridMember.getId(), gridId);
            if (gridDto == null) {
                return Response.error("没有查询到该网格信息");
            }
        }

        try {
            Calendar calendar = CalendarUtil.parseByPatterns(dateParam, DatePattern.NORM_MONTH_PATTERN);

            Map<String, Object> params = new HashMap<>(4);
            params.put(LOG_DATE_SLOT_KEY_PAIR.getLeft(), DateUtil.format(DateUtil.beginOfMonth(calendar.getTime()), DatePattern.NORM_DATE_FORMATTER));
            params.put(LOG_DATE_SLOT_KEY_PAIR.getRight(), DateUtil.format(DateUtil.endOfMonth(calendar.getTime()), DatePattern.NORM_DATE_FORMATTER));
            params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
            params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());
            if (gridDto != null) {
                params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridId), gridDto.getId());
            }

            List<Date> dates = gridMemberWorkLogService.logDates(params);
            List<String> collect = dates.stream().map(value -> DateUtils.format(value, DateUtils.FormatType.SIMPLE)).collect(Collectors.toList());
            return Response.<List<String>>ok().wrap(collect);
        } catch (DateException e) {
            return Response.error("日期格式不正确");
        }
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @Operation(summary = "分页列表")
    public Response<Page<GridMemberWorkLogDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "网格ID") @RequestParam(required = false) Long gridId,
            @Parameter(description = "查询日期,格式yyyy-MM-dd") @RequestParam(required = false) String dateParam

    ) {
        GridMemberDto gridMember = SessionHolder.getGridMember();
        GridDto gridDto = null;
        if (gridId != null) {
            gridDto = gridBusiness.checkGridMemberPermission(gridMember.getId(), gridId);
            if (gridDto == null) {
                return Response.error("没有查询到该网格信息");
            }
        }

        try {
            if (StringUtils.isNotEmpty(dateParam)) {
                CalendarUtil.parseByPatterns(dateParam, DatePattern.NORM_DATE_PATTERN);
            }

            //查询列表数据
            Request request = Request.configParams(Request.parseParams(httpServletRequest));
            request.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
            request.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());
            request.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getLogDate), dateParam);

            if (gridDto != null) {
                request.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridId), gridDto.getId());
            }

            int total = gridMemberWorkLogService.queryTotal(request.getParams());

            List<GridMemberWorkLogDto> list = null;
            if (total > 0) {
                list = gridMemberWorkLogService.queryListWithNoPadding(request.getParams());
            } else {
                list = new ArrayList<>();
            }

            Page<GridMemberWorkLogDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
            return Response.<Page<GridMemberWorkLogDto>>ok().wrap(page);


        } catch (Exception e) {
            return Response.error("查询日期格式不正确");
        }

    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @Operation(summary = "查询单条记录")
    public Response<GridMemberWorkLogDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

        GridMemberDto gridMember = SessionHolder.getGridMember();

        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());

        if (gridMemberWorkLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridMemberWorkLogDto gridMemberWorkLogDto = gridMemberWorkLogService.selectByIdWithNoPadding(id);

        return Response.<GridMemberWorkLogDto>ok().wrap(gridMemberWorkLogDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @Operation(summary = "查询单条记录")
    public Response<GridMemberWorkLogDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();

        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

        GridMemberDto gridMember = SessionHolder.getGridMember();

        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());
        if (gridMemberWorkLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridMemberWorkLogDto gridMemberWorkLogDto = gridMemberWorkLogService.selectByIdWithNoPadding(id);

        return Response.<GridMemberWorkLogDto>ok().wrap(gridMemberWorkLogDto);
    }

    /**
     * 保存
     *
     * @param gridMemberWorkLogDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "gridMemberWorkLog:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated GridMemberWorkLogDto gridMemberWorkLogDto) {
        GridMemberDto gridMember = SessionHolder.getGridMember();
        GridDto gridDto = gridService.selectById(gridMemberWorkLogDto.getGridId());

        gridMemberWorkLogDto.setTenantId(gridDto.getTenantId());
        gridMemberWorkLogDto.setVillageId(gridDto.getVillageId());
        gridMemberWorkLogDto.setGridId(gridDto.getId());
        gridMemberWorkLogDto.setGridMemberId(gridMember.getId());
        Date now = new Date();
        gridMemberWorkLogDto.setCreateTime(now);

        gridMemberWorkLogService.save(gridMemberWorkLogDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridMemberWorkLogDto
     * @return
     */
    @PostMapping("update")
    @Operation(summary = "修改单条记录detail")
    public Response<Object> update(@RequestBody @Validated GridMemberWorkLogDto gridMemberWorkLogDto) {

        Map<String, Object> params = new HashMap<>();

        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridMemberWorkLogDto.getId()));

        GridMemberDto gridMember = SessionHolder.getGridMember();

        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getTenantId), gridMember.getTenantId());
        params.put(LambdaUtil.getFieldName(GridMemberWorkLogDto::getGridMemberId), gridMember.getId());

        if (gridMemberWorkLogService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridMemberWorkLogDto dbDto = gridMemberWorkLogService.selectByIdWithNoPadding(gridMemberWorkLogDto.getId());
        dbDto.setDetail(gridMemberWorkLogDto.getDetail());
        dbDto.setUpdateTime(DateTime.now());

        gridMemberWorkLogService.updateById(dbDto);

        return Response.ok();
    }


}
